package com.example.gty.service.Impl;

import com.example.gty.entity.*;
import com.example.gty.mapper.*;
import com.example.gty.service.TeacherService;
import com.example.gty.utils.ResultVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.util.*;

@Service
public class TeacherServiceImpl implements TeacherService {
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private TeacherCourseMapper teacherCourseMapper;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private RolePremissionMapper rolePremissionMapper;
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    private ObjectMapper objectMapper = new ObjectMapper();

    //查询老师所有信息及所交课程
    public ResultVo selectAllTeacher() {
        List<TeacherVo> teacherVos = teacherMapper.selectTeacher();
        return new ResultVo<List<TeacherVo>>(1000, "success", teacherVos);
    }

    //关键字查询老师信息
    public ResultVo selectTeaKey(String key) {
        /*String s = "%" + key + "%";
        List<TeacherVo> teacherVos = teacherMapper.selectTeaKey(s);
        if (teacherVos != null && teacherVos.size() > 0) {
            return new ResultVo(1000, "success", teacherVos);
        } else {
            return new ResultVo(1001, "error", null);
        }*/
        try {
            List<TeacherVo> list=new ArrayList<>();
        SearchRequest searchRequest = new SearchRequest("teacherinfo");
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            //搜索内容 字段
            searchSourceBuilder.query(QueryBuilders.multiMatchQuery(key,"tno","tname","sex","tel","cnames"));

            //设置高亮内容
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            HighlightBuilder.Field field1=new HighlightBuilder.Field("tno");
            HighlightBuilder.Field field2=new HighlightBuilder.Field("tname");
            HighlightBuilder.Field field3=new HighlightBuilder.Field("sex");
            HighlightBuilder.Field field4=new HighlightBuilder.Field("tel");
            HighlightBuilder.Field field5=new HighlightBuilder.Field("cnames");


            highlightBuilder.field(field1);
            highlightBuilder.field(field2);
            highlightBuilder.field(field3);
            highlightBuilder.field(field4);
            highlightBuilder.field(field5);
            //设置样式
            highlightBuilder.preTags("<font color='red' size='60px'>");
            highlightBuilder.postTags("</font>");

            searchSourceBuilder.highlighter(highlightBuilder);
            searchRequest.source(searchSourceBuilder);

            SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            //解析查询结果
            SearchHits hits = search.getHits();
          //  hits.getTotalHits().value;获取信息条数
            Iterator<SearchHit> iterator = hits.iterator();
            while (iterator.hasNext()) {
                SearchHit hit = iterator.next();
                //System.err.println(hit);

                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                String tea = hit.getSourceAsString();
                TeacherVo teacherVo = objectMapper.readValue(tea, TeacherVo.class);
                if (highlightFields.get("tno")!=null){
                    teacherVo.setTno(Arrays.toString(highlightFields.get("tno").fragments()));
                }
                if (highlightFields.get("tname")!=null){
                    teacherVo.setTname(Arrays.toString(highlightFields.get("tname").fragments()));
                }
                if (highlightFields.get("sex")!=null){
                    teacherVo.setSex(Arrays.toString(highlightFields.get("sex").fragments()));
                }
                if (highlightFields.get("tel")!=null){
                    teacherVo.setTel(Arrays.toString(highlightFields.get("tel").fragments()));
                }
                if (highlightFields.get("cnames")!=null){
                    List<String> ls=new ArrayList<>();
                    ls.add(Arrays.toString(highlightFields.get("cnames").fragments()));
                    teacherVo.setCnames(ls);
                }
                list.add(teacherVo);

            }
            return new ResultVo(1000,"success",list);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //修改老师基本信息
    public ResultVo updateTeacher(Teacher teacher) {
        teacher.setCreateTime(new Date());
        int i = teacherMapper.updateByPrimaryKey(teacher);
        if (i > 0) {
            return new ResultVo(1000, "success", null);
        } else {
            return new ResultVo(1001, "error", null);
        }
    }

    //删除老师
    public ResultVo deleteTeacher(String tno) {


        //删除老师基本信息表中信息
        int i = teacherMapper.deleteByPrimaryKey(tno);
        //删除老师课程表中信息
        Example example = new Example(TeacherCourse.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("tno", tno);
        int i1 = teacherCourseMapper.deleteByExample(example);
        //删除用户表中的老师
        int i2 = usersMapper.deleteByPrimaryKey(tno);
        //删除用户角色表中老师
        Example example1 = new Example(UserRole.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andEqualTo("no", tno);
        int i3 = userRoleMapper.deleteByExample(example1);
        //删除角色权限表
        Example example2 = new Example(RolePremission.class);
        Example.Criteria criteria2 = example2.createCriteria();
        criteria2.andEqualTo("role",tno);
        rolePremissionMapper.deleteByExample(example2);

        if (i > 0 && i2 > 0 && i3 > 0) {
            //删除es
            DeleteRequest request = new DeleteRequest("teacherinfo");
            request.id(tno);
            try {
                DeleteResponse delete = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return new ResultVo(1000, "success", null);
        } else {
            return new ResultVo(1001, "error", null);
        }
    }

    //添加老师信息
    public ResultVo addTeacher(Teacher teacher, String email) {
        //用户表中添加老师账号 密码默认123
        // int i1 = teacherMapper.addTeacherInUser(teacher, email);
        teacher.setImg("2131099767");
        if (teacherMapper.selectByPrimaryKey(teacher.getTno()) != null) {
            return new ResultVo(1001, "erro", null);
        } else {
            Users users = new Users();
            users.setId(Long.parseLong(teacher.getTno()));
            users.setNo(teacher.getTno());
            users.setPassword("123");
            users.setEmail(email);
            int i1 = usersMapper.insertSelective(users);
            //用户角色表中添加老师信息
            UserRole userRole = new UserRole(teacher.getTno(), "教师");
            int i2 = userRoleMapper.insert(userRole);
            //老师基本信息表中添加
            teacher.setCreateTime(new Date());
            System.out.println(teacher);
            int i3 = teacherMapper.insert(teacher);
            //角色权限表
            rolePremissionMapper.insert(new RolePremission(teacher.getTno(),""));
            if (i1 > 0 && i2 > 0 && i3 > 0) {
                //添加es
                IndexRequest request = new IndexRequest("teacherinfo");
                request.id(teacher.getTno());
                try {
                    request.source(objectMapper.writeValueAsString(teacher),XContentType.JSON);
                    IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                return new ResultVo(1000, "success", null);
            } else {
                return new ResultVo(1001, "error", null);
            }
        }
    }

    //添加老师所授课程
    public ResultVo addTeacherCourse(String tno, String cno) {
        //先查一遍 是否存在
        Example example = new Example(TeacherCourse.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("tno", tno);
        criteria.andEqualTo("cno", cno);
        List<TeacherCourse> list = teacherCourseMapper.selectByExample(example);
        if (list == null || list.size() <= 0) {
            TeacherCourse tc = new TeacherCourse(tno, cno);

            int i = teacherCourseMapper.insert(tc);
            if (i > 0) {
                return new ResultVo(1000, "success", null);
            } else {
                return new ResultVo(1001, "error1", null);
            }
        } else {
            return new ResultVo(1001, "error2", null);
        }

    }

    //批量导入学生信息
    public void importStudentInfo(List<Student> list) {
        for (int i = 0; i < list.size(); i++) {
            //用户表加入数据
            Student student = list.get(i);
            String sno = student.getSno();
            Date createTime = student.getCreateTime();
            //添加学生信息时 加入es 搜索 引擎中
            IndexRequest request = new IndexRequest("studentinfo");
            try {
                request.id(list.get(i).getSno());
                request.source(objectMapper.writeValueAsString(list.get(i)), XContentType.JSON);
                restHighLevelClient.index(request, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
            }

            int i1 = usersMapper.insertSelective(new Users(Long.parseLong(sno), sno, "123", ""));
            //用户角色表加入数据
            int i2 = userRoleMapper.insert(new UserRole(sno, "学生"));
            //学生表中加入数据
            int i3 = studentMapper.insert(student);

        }
    }
}
